package com.gp.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.gp.dao.MenuDao;
import com.gp.dao.UserDao;
import com.gp.entity.Menu;
import com.gp.entity.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author 来一杯凉咖
 * @create 2022/3/10 17:08
 */
@Service
public class UserServiceImpl implements UserDetailsService {
    @Autowired
    private UserDao userDao;
    @Autowired
    private MenuDao menuDao;
    @Override
    public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
        //根据用户名查询用户信息
        QueryWrapper<User> wrapper=new QueryWrapper<>();
        wrapper.eq("user_name",s);
        User user = userDao.selectOne(wrapper);
        if(user!=null){
            //为该账号赋值权限
            List<Menu> menus= menuDao.findMenuByRoleId(user.getUserId());
            List<SimpleGrantedAuthority> authorities=
                    menus.stream().
                            map(item->new SimpleGrantedAuthority(item.getUrl()))
                            .collect(Collectors.toList());
            user.setAuthorities(authorities);
        }
        return user;
    }
}
